'''
''' event handler for Button that downloads
''' myfile.txt from a subfolder called Data in the current directory.
'''
Public Overrides Sub ${Download Button Control}_Click(ByVal sender As Object, ByVal args As EventArgs)
' Specify the name of the file, located in the
' file system, that needs to be downloaded.
Dim fileName As String = "myfile.txt"
' Check if file exists in the file system.
Dim fileExists As Boolean = System.IO.File.Exists(Me.Page.Server.MapPath("..\Data") + "\" + fileName)
If fileExists Then
' Set up file stream object.
Dim fs As System.IO.FileStream
fs = New System.IO.FileStream( _
Me.Page.Server.MapPath("..\Data") + "\" + fileName, _
System.IO.FileMode.Open, _
System.IO.FileAccess.Read, _
System.IO.FileShare.Read)
Dim fullFileName As String = Me.Page.Server.MapPath("..\Data") + "\" + fileName
Try
' Read the contents of the file.
Dim bufSize As Integer = CType(fs.Length, Integer)
Dim buf(bufSize) As Byte
Dim bytesRead As Integer = fs.Read(buf, 0, bufSize)
' Set up parameters for file download.
Me.Page.Response.ContentType = "application/octet-stream"
Me.Page.Response.AppendHeader("Content-Disposition", "attachment;filename=" + fileName)
' Download the file.
Me.Page.Response.OutputStream.Write(buf, 0, bytesRead)
Me.Page.Response.Flush()
Catch ex As Exception
' Report the error message to the user
Utils.MiscUtils.RegisterJScriptAlert(Me, "UNIQUE_SCRIPTKEY", ex.Message)
Finally
fs.Close
End Try
Else
Me.Page.Response.Write("File cannot be found to download")
End If
End Sub
|